<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form px-[15px] py-[15px] flex">
      <div class="w-[160px]">
        <el-input v-model="form.nickname" placeholder="用户名/昵称" />
      </div>
      <div class="w-[160px] ml-[10px]">
        <el-select class="!w-full" v-model="form.action" placeholder="排序类型">
          <el-option
            v-for="item in action"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="w-[160px] ml-[10px]">
        <el-select class="!w-full" v-model="form.status" placeholder="选择状态">
          <el-option label="全部状态" value="-1" />
          <el-option label="禁用" value="0" />
          <el-option label="正常" value="1" />
          <el-option label="禁言" value="2" />
          <el-option label="禁止加入" value="3" />
        </el-select>
      </div>
      <div class="flex ml-[15px]">
        <el-button type="primary" @click.stop="search">搜索</el-button>
        <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
        <el-button type="success" icon="Delete" @click="delZeroCoinUser">一键清空0分用户</el-button>
        <div class="flex items-center ml-[10px]">
          <span class="text-[14px] mr-[5px]">是否显示0分用户</span>
          <el-switch v-model="form.showZero" :active-value="1" :inactive-value="0" />
        </div>
      </div>
      <div class="ml-auto">
        <section class="flex items-center mt-[5px]">
          <el-button type="primary" size="small" round @click="getData">刷新</el-button>
          <div class="w-[80px] text-center mx-[10px]">
            {{ count == 0 ? "手动" : count + "秒" }}
          </div>
          <el-select v-model="userTimer" size="small">
            <el-option
              size="small"
              v-for="item in timerList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </section>
      </div>
    </div>
    <div class="grow-[1] h-0 mx-[15px]">
      <el-table
        scrollbar-always-on
        ref="elTableRef"
        v-loading="state.loading"
        :data="list"
        height="100%"
        row-key="UserId"
        highlight-current-row
        :expand-row-keys="expands"
        @expand-change="expandColumn"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column align="center" type="expand" width="0">
          <template #default="{ row }: TableItem">
            <div class="flex justify-start px-[10px] py-[0px]">
              <el-button type="success" size="small" @click="openDialog('member', row)">
                会员资料
              </el-button>
              <el-button type="success" size="small" @click.stop="openChat(row)"> 私信 </el-button>
              <el-button
                :type="row.IsSpecialBackwater === 1 ? 'success' : 'default'"
                size="small"
                @click="openDialog('backwater', row)"
              >
                回水比例
              </el-button>
              <el-button type="success" size="small" @click.stop="openReportDetail(row)">
                报表详情
              </el-button>
              <el-button
                v-if="premsStore.isApplyUpdown"
                type="success"
                size="small"
                @click="openDialog('updown', row)"
              >
                分数操作
              </el-button>
              <el-button
                v-if="row.Type !== 2"
                type="success"
                size="small"
                @click="openDialog('redpacket', row)"
              >
                发红包
              </el-button>
              <el-button
                v-if="row.Type === 1 && !row.ParentId"
                type="success"
                size="small"
                @click="openDialog('setagent', row)"
              >
                设置代理
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="openDialog(row.IsBehalf === 1 ? 'cancel_behalf' : 'setbehalf', row)"
              >
                {{ row.IsBehalf === 1 ? "取消代注" : "设置代注" }}
              </el-button>
              <el-button type="success" size="small" @click="openDialog('setpass', row)">
                修改密码
              </el-button>
              <el-button type="danger" size="small" @click="openDialog('resetpass', row)">
                重置下分密码
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="openDialog(row.Status === 2 ? 'cancel_forbidden' : 'forbidden', row)"
              >
                {{ row.Status === 2 ? "解除禁言" : "禁言" }}
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="openDialog(row.Status === 3 ? 'cancel_banroom' : 'banroom', row)"
              >
                {{ row.Status === 3 ? "解除禁止加入房间" : "禁止加入房间" }}
              </el-button>
              <el-button type="danger" size="small" @click="openDialog('deluser', row)">
                删除用户
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="在线" width="60">
          <template #default="{ row }: TableItem">
            <div
              class="h-[10px] w-[10px] rounded-full mx-auto"
              :class="{
                'bg-gray-300': row.Online === 0,
                'bg-[#67C23A]': row.Online === 1
              }"
            ></div>
          </template>
        </el-table-column>
        <el-table-column align="center" class="avatar" prop="Avatar" label="头像" width="70">
          <template #default="{ row }: TableItem">
            <div class="flex items-center justify-center">
              <el-badge class="h-[30px]">
                <avatar :size="30" :src="row.Avatar" />
              </el-badge>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Note" label="会员备注" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Note || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Name" label="用户名" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Name || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Nickname" label="昵称" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Nickname || "--" }}
          </template>
        </el-table-column>

        <el-table-column align="center" prop="Coin" label="余额" min-width="120">
          <template #default="{ row }: TableItem">
            <ui-amount :num="row.Coin" />
          </template>
        </el-table-column>
        <el-table-column align="center" props="IsBehalf" label="是否代注" width="90">
          <template #default="{ row }: TableItem">
            <span :class="row.IsBehalf == 1 ? 'text-green' : ''">{{
              row.IsBehalf == 1 ? "是" : "否"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" props="IsFollow" label="是否关注" width="90">
          <template #default="{ row }: TableItem">
            <el-dropdown placement="bottom" @command="(e: number) => handleChangeFollow(row, e)">
              <el-button :type="row.IsFollow == 1 ? 'success' : 'default'" size="small">
                关注
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="row.IsFollow == 1" :command="1">
                    <div class="w-full text-center">关注</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.IsFollow == 0" :command="0">
                    <div class="w-full text-center">取消关注</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column prop="Status" align="center" label="账号状态" min-width="100">
          <template #default="{ row }: TableItem">
            <el-dropdown placement="bottom" @command="(e: number) => handleChangeStatus(row, e)">
              <el-button :type="statusMap[row.Status].type" size="small">
                {{ statusMap[row.Status].text }}
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :disabled="row.Status == 1" :command="1">
                    <div class="w-full text-center">正常</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.Status == 0" :command="0">
                    <div class="w-full text-center">停用</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.Status == 2" :command="2">
                    <div class="w-full text-center">禁言</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="row.Status == 3" :command="3">
                    <div class="w-full text-center">禁止加入房间</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column prop="Type" align="center" label="账号类型" width="100">
          <template #default="{ row }: TableItem">
            <el-button :type="userTypeMap[row.Type]?.type" size="small">
              {{ userTypeMap[row.Type]?.text }} {{ row.Type == 5 ? `(${row.Level})` : "" }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="回水设置" align="center" width="110">
          <template #default="{ row }: TableItem">
            <el-button
              :type="row.IsSpecialBackwater === 1 ? 'success' : 'default'"
              size="small"
              @click="openDialog('backwater', row)"
            >
              回水比例
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="分数操作"
          align="center"
          width="110"
          v-if="premsStore.isApplyUpdown"
        >
          <template #default="{ row }: TableItem">
            <el-button type="success" size="small" @click="openDialog('updown', row)">
              分数操作
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="110">
          <template #default="{ row }: TableItem">
            <el-button type="success" size="small" @click.stop="expandColumn(row)">
              更多操作
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px] mx-[15px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <private-chat-dialog
      ref="privateChatDialogRef"
      :username="currentData?.Name"
      :uid="currentData?.UserId"
    />
    <member-info-dialog ref="memberInfoDialogRef" :uid="currentData?.UserId" @update="getData" />
    <backwater-dialog
      ref="backwaterDialogRef"
      :uid="currentData?.UserId"
      :username="currentData?.Name"
      :is-special-backwater="currentData?.IsSpecialBackwater"
      @update="getData"
    />
    <point-dialog
      ref="pointDialogRef"
      :uid="currentData?.UserId"
      :username="currentData?.Name"
      @update="getData"
    />
    <red-packet-dialog
      ref="redPacketDialogRef"
      type="add"
      :uid="currentData?.UserId"
      :username="currentData?.Name"
    />
    <edit-password-dialog
      ref="editPasswordDialogRef"
      :uid="currentData?.UserId"
      :username="currentData?.Name"
      @update="getData"
    />
    <report-detail-dialog
      ref="reportDetailDialogRef"
      :uid="currentData?.UserId"
      :name="currentData?.Name"
    />
  </div>
</template>
<script setup lang="ts">
import PrivateChatDialog from "./components/private-chat-dialog.vue";
import MemberInfoDialog from "./components/member-info-dialog.vue";
import BackwaterDialog from "./components/backwater-dialog.vue";
import PointDialog from "./components/point-dialog.vue";
import RedPacketDialog from "@/components/red-packet-dialog.vue";
import EditPasswordDialog from "./components/edit-password-dialog.vue";
import ReportDetailDialog from "./components/report-detail-dialog.vue";

import $bus from "@/utils/bus";
import { useList } from "@/hooks/useList";
import {
  reqDelZeroCoinUser,
  reqUserBan,
  reqUserBecomeAgent,
  reqUserBehalf,
  reqUserDel,
  reqUserFollow,
  reqUserList,
  reqUserUpdateWithdrawPassword
} from "@/api/user";
import { ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash-es";
import { message } from "@/utils/message";
import { useTimerStore } from "@/store/modules/timer";
import { storeToRefs } from "pinia";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: MemberMo;
}

const form = reactive({
  action: "coin__desc",
  status: "-1",
  showZero: <1 | 0>1,
  nickname: "",
  userNo: ""
});

const premsStore = usePremsStore();
const expands = ref<number[]>([]);
let timer: any;
const timerStore = useTimerStore();
const { timerList, userTimer } = storeToRefs(timerStore);
const count = ref(userTimer.value);

const action = ref([
  { name: "余额降序", value: "coin__desc" },
  { name: "余额升序", value: "coin__asc" },
  { name: "会员ID降序", value: "id__desc" },
  { name: "会员ID升序", value: "id__asc" }
]);

const userTypeMap = reactive<Record<string, TextType>>({
  1: { text: "会员", type: "primary" },
  2: { text: "游客", type: "info" },
  3: { text: "机器人", type: "warning" },
  4: { text: "房主", type: "danger" },
  5: { text: "代理", type: "success" }
});
const statusMap = reactive<Record<string, TextType>>({
  0: { text: "停用", type: "danger" },
  1: { text: "正常", type: "success" },
  2: { text: "禁言", type: "danger" },
  3: { text: "禁止加入房间", type: "danger" }
});

const currentData = ref<MemberMo | null>(null);
const privateChatDialogRef = ref();
const memberInfoDialogRef = ref();
const backwaterDialogRef = ref();
const pointDialogRef = ref();
const redPacketDialogRef = ref();
const editPasswordDialogRef = ref();
const reportDetailDialogRef = ref();

// 获取参数
const getParams = () => {
  const [Order, By] = form.action.split("__");
  const params: MemberParams = {
    Order,
    By,
    ShowZero: form.showZero
  };
  if (form.status && form.status != "-1") {
    params.Status = form.status;
  }
  if (form.nickname) {
    params.Nickname = form.nickname;
  }
  if (form.userNo) {
    params.UserNo = form.userNo;
  }
  return params;
};
const { elTableRef, state, list, getData, search } = useList<MemberMo, MemberParams>(
  reqUserList,
  getParams
);

const handleRefresh = () => {
  form.nickname = "";
  form.userNo = "";
  form.action = "coin__desc";
  search();
};

// 展开行
const expandColumn = (row: MemberMo) => {
  if (!expands.value.includes(row.UserId)) {
    expands.value.push(row.UserId);
  } else {
    expands.value = expands.value.filter(id => id !== row.UserId);
  }
};

// 弹框操作
const doConfirm = (callback: Function, text: string) => {
  ElMessageBox.confirm(text, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await callback(done);
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

// 更多操作
const openDialog = (type: string, row: MemberMo) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    if (type == "member") {
      memberInfoDialogRef.value?.open();
    } else if (type == "backwater") {
      backwaterDialogRef.value?.open();
    } else if (type == "updown") {
      pointDialogRef.value?.open();
    } else if (type == "redpacket") {
      redPacketDialogRef.value?.open();
    } else if (type == "forbidden") {
      doConfirm(async (done: Function) => await forbidden(row, 2, done), "是否进行【禁言】操作？");
    } else if (type == "cancel_forbidden") {
      doConfirm(async (done: Function) => forbidden(row, 1, done), "是否进行【解除禁言】操作？");
    } else if (type == "banroom") {
      doConfirm(
        async (done: Function) => banJoinRoom(row, 3, done),
        "是否进行【禁止加入房间】操作？"
      );
    } else if (type == "cancel_banroom") {
      doConfirm(
        async (done: Function) => banJoinRoom(row, 1, done),
        "是否进行【解除禁止加入房间】操作？"
      );
    } else if (type == "deluser") {
      doConfirm(async (done: Function) => await delUser(row, done), "是否进行【删除用户】操作？");
    } else if (type == "setagent") {
      doConfirm(async (done: Function) => await setAgent(row, done), "是否设置该会员为代理？");
    } else if (type == "setbehalf") {
      doConfirm(async (done: Function) => await setBehalf(row, done), "是否设置该会员为代注会员？");
    } else if (type == "cancel_behalf") {
      doConfirm(async (done: Function) => await setBehalf(row, done), "是否取消该会员为代注会员？");
    } else if (type == "resetpass") {
      doConfirm(
        async (done: Function) => await resetPass(row, done),
        "是否进行【重置下分密码】操作？"
      );
    } else if (type == "setpass") {
      editPasswordDialogRef.value?.open();
    }
  });
};

// 打开发送私信
const openChat = (row: any) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    privateChatDialogRef.value?.open();
  });
};

// 打开报表详情
const openReportDetail = (row: any) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    reportDetailDialogRef.value?.open();
  });
};

// 一键删除0分用户
const delZeroCoinUser = () => {
  doConfirm(async (done: Function) => {
    try {
      await reqDelZeroCoinUser();
      message.success("删除0分用户成功");
      getData();
      done();
    } catch (error) {
      console.log(error);
    }
  }, "【一键删除0分用户】");
};

// 禁言操作
const forbidden = async (row: MemberMo, Status: 0 | 1 | 2 | 3, done: Function) => {
  try {
    await reqUserBan({
      UserId: row.UserId,
      Status
    });
    message.success(Status == 2 ? "禁言成功" : "解除禁言成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 禁止加入房间
const banJoinRoom = async (row: MemberMo, Status: 0 | 1 | 2 | 3, done: Function) => {
  try {
    await reqUserBan({
      UserId: row.UserId,
      Status
    });
    message.success(Status == 3 ? "禁止加入房间成功" : "解除禁止加入房间成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 删除用户
const delUser = async (row: MemberMo, done: Function) => {
  try {
    await reqUserDel(row.UserId);
    message.success("删除用户成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 设置代理
const setAgent = async (row: MemberMo, done: Function) => {
  try {
    await reqUserBecomeAgent({
      UserId: row.UserId
    });
    message.success("设置代理成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 设置代注
const setBehalf = async (row: MemberMo, done: Function) => {
  try {
    await reqUserBehalf({
      UserId: row.UserId,
      IsBehalf: row.IsBehalf == 1 ? 0 : 1
    });
    message.success(row.IsBehalf == 1 ? "取消代注成功" : "设置代注成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 重置下分密码
const resetPass = async (row: MemberMo, done: Function) => {
  try {
    await reqUserUpdateWithdrawPassword(row.UserId);
    message.success("重置下分密码成功");
    getData();
    done();
  } catch (error) {
    console.log(error);
  }
};

// 修改状态
const handleChangeStatus = async (row: MemberMo, key: number) => {
  try {
    state.loading = true;
    await reqUserBan({
      UserId: row.UserId,
      Status: key
    });
    message.success("修改状态成功");
    state.loading = false;
    row.Status = key;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

// 关注/取消关注
const handleChangeFollow = async (row: MemberMo, key: number) => {
  try {
    state.loading = true;
    await reqUserFollow({
      UserId: row.UserId,
      IsFollow: key
    });
    message.success(key == 1 ? "关注成功" : "取消关注成功");
    state.loading = false;
    row.IsFollow = key;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const setTimer = () => {
  clearInterval(timer);
  timer = null;
  if (userTimer.value > 0) {
    timer = setInterval(() => {
      count.value--;
      if (count.value == 0) {
        count.value = userTimer.value;
        getData();
      }
    }, 1000);
  } else {
    clearInterval(timer);
    timer = null;
    count.value = 0;
  }
};
watch(
  () => userTimer.value,
  val => {
    count.value = val;
    nextTick(setTimer);
  }
);
watch(
  () => form.showZero,
  () => {
    handleRefresh();
  }
);
onMounted(() => {
  getData();
  setTimer();
  $bus.on("update-member-msg", () => {
    getData();
  });
});
onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});
</script>
<style lang="scss" scoped>
:deep(.el-table__row) {
  cursor: pointer;
}
</style>
